package com.example.weight.greenSeasons.SolidLiquid;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SolidLiquidMonthMaintenanceActivity extends AppCompatActivity {

    private String name, fName, factory;

    private List<RadioButton> normalButtons;
    private List<RadioButton> abnormalButtons;
    private List<TextView> names;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_solidliquid_month_maintenance);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");//具体维护项
        fName = previousIntent.getStringExtra("fName");//保养机器名称
        factory = previousIntent.getStringExtra("factory");

        LinearLayout group4 = findViewById(R.id.solidliquid_group4);

        //正常异常按钮组
        RadioGroup radioGroup1 = findViewById(R.id.equipment1_group_button);
        RadioGroup radioGroup2 = findViewById(R.id.equipment2_group_button);
        RadioGroup radioGroup3 = findViewById(R.id.equipment3_group_button);
        RadioGroup radioGroup4 = findViewById(R.id.equipment4_group_button);
        List<RadioGroup> radioGroups = new ArrayList<>();
        radioGroups.add(radioGroup1);   radioGroups.add(radioGroup2);
        radioGroups.add(radioGroup3);   radioGroups.add(radioGroup4);

        //1正常按钮，0异常按钮
        RadioButton btn1_1 = findViewById(R.id.equipment1_normal_button);
        RadioButton btn1_0 = findViewById(R.id.equipment1_abnormal_button);
        RadioButton btn2_1 = findViewById(R.id.equipment2_normal_button);
        RadioButton btn2_0 = findViewById(R.id.equipment2_abnormal_button);
        RadioButton btn3_1 = findViewById(R.id.equipment3_normal_button);
        RadioButton btn3_0 = findViewById(R.id.equipment3_abnormal_button);
        RadioButton btn4_1 = findViewById(R.id.equipment4_normal_button);
        RadioButton btn4_0 = findViewById(R.id.equipment4_abnormal_button);
        normalButtons = new ArrayList<>();
        normalButtons.add(btn1_1);  normalButtons.add(btn2_1);
        normalButtons.add(btn3_1);  normalButtons.add(btn4_1);
        abnormalButtons = new ArrayList<>();
        abnormalButtons.add(btn1_0); abnormalButtons.add(btn2_0);
        abnormalButtons.add(btn3_0); abnormalButtons.add(btn4_0);

        //保养内容
        TextView name1 = findViewById(R.id.item1);
        TextView name2 = findViewById(R.id.item2);
        TextView name3 = findViewById(R.id.item3);
        TextView name4 = findViewById(R.id.item4);
        names = new ArrayList<>();
        names.add(name1);   names.add(name2);   names.add(name3);   names.add(name4);

        //月保养标题栏
        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setTitle(fName+"保养内容");
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }
            @Override
            public void onTitleClick(View v) {}
            @Override
            public void onRightClick(View v) {}
        });

        //日期设置
        TextView actualDate = findViewById(R.id.worm_incoming_incomeDate);
        String tempText = actualDate.getText().toString();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        actualDate.setText(tempText+year+"-"+month+"-"+day);

        // 根据不同系统名称，设置不同保养内容
        switch (fName) {
            case "1#对接口":
            case "2#对接口":
                initialCheckStatus();
                break;
            case "1#固液分离机":
            case "2#固液分离机":
                //setVisibility():
                //有三个参数：Parameters:visibility One of VISIBLE, INVISIBLE, or GONE，对应的三个常量值：0、4、8
                //VISIBLE:0  意思是可见的
                //INVISIBILITY:4 意思是不可见的，但还占着原来的空间
                //GONE:8  意思是不可见的，不占用原来的布局空间
                group4.setVisibility(View.GONE);
                name1.setText("紧固螺栓");
                name2.setText("除锈刷漆");
                name3.setText("检查耙齿");
                initialCheckStatus();
                break;
            case "1#控制系统":
            case "2#控制系统":
                name1.setText("内部除尘处理");
                name2.setText("检查电器性能");
                name3.setText("更换频次过高的开关");
                name4.setText("大保养更换老化信号线");
                initialCheckStatus();
                break;
            case "无轴螺旋输送机":
                group4.setVisibility(View.GONE);
                name1.setText("检测电动机电流值喷漆保养");
                name2.setText("更换减速机齿轮油");
                name3.setText("两年更换一次衬板");
                initialCheckStatus();
                break;
        }

        // maintain content
        for (int i = 0; i < names.size(); i++) {
            String eqName = names.get(i).getText().toString();
            RadioButton normal = normalButtons.get(i), abnormal = abnormalButtons.get(i);
            RadioGroup group = radioGroups.get(i);
            normal.setOnClickListener(v -> {
                if (normal.isChecked()) {
                    saveNormal(eqName, normal, abnormal, group);
                }
            });
            abnormal.setOnClickListener(v -> {
                if (abnormal.isChecked()) {
                    saveAbnormal(eqName, normal, abnormal, group);
                }
            });
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        Intent intent = new Intent();
        intent.putExtra("needRefresh", true);
        setResult(RESULT_OK, intent);
    }

    private void initialCheckStatus() {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/solidliquidProduceMaintenanceMonth/getMonthRecords";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("lctest", response);
                            JSONObject jsonObject = new JSONObject(response);
                            if(!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if(data.length() > 0){
                                    for(int i = 0; i < data.length(); i++){
                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                        JSONObject record = data.getJSONObject(i);
                                        // 得到 每个对象中的属性值
                                        for (int j = 0; j < names.size(); j++) {
                                            String maintainContent = names.get(j).getText().toString();
                                            RadioButton normal = normalButtons.get(j);
                                            RadioButton abnormal = abnormalButtons.get(j);
                                            if (record.getString("maintenanceContent")
                                                    .equals(maintainContent)) {
                                                if(record.get("isNormal").equals("正常")){
                                                    normal.setChecked(true);
                                                }else {
                                                    abnormal.setChecked(true);
                                                }
                                                if(!record.isNull("operator")){
                                                    normal.setClickable(false);
                                                    abnormal.setClickable(false);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(SolidLiquidMonthMaintenanceActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipment_name", fName);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    public void saveNormal(String maintainContent, RadioButton normal_rb, RadioButton abnormal_rb, RadioGroup rb) {
        new AlertDialog.Builder(this)
                .setTitle("确定 “"+ maintainContent +"” 正常？")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    rb.clearCheck();
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/solidliquidProduceMaintenanceMonth/add_recorder";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Toast.makeText(SolidLiquidMonthMaintenanceActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else {
                                            Toast.makeText(SolidLiquidMonthMaintenanceActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                            normal_rb.setChecked(false);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(SolidLiquidMonthMaintenanceActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", fName);
                            map.put("maintenance_content", maintainContent);
                            map.put("isNormal","正常");
                            map.put("remarks", "");
                            map.put("operator", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void saveAbnormal(String maintainContent, RadioButton normal_rb, RadioButton abnormal_rb, RadioGroup rb) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new AlertDialog.Builder(this)
                .setTitle("请填写 “"+ maintainContent +"” 异常原因？")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    rb.clearCheck();
                }
                ))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/solidliquidProduceMaintenanceMonth/add_recorder";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Toast.makeText(SolidLiquidMonthMaintenanceActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else {
                                            Toast.makeText(SolidLiquidMonthMaintenanceActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                            abnormal_rb.setChecked(false);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(SolidLiquidMonthMaintenanceActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", fName);
                            map.put("maintenance_content", maintainContent);
                            map.put("isNormal","异常");
                            map.put("remarks", equipment_problem.getText().toString());
                            map.put("operator", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}